package com.lz.c;

import java.util.Scanner;

/**
 * @ClassName Demo22
 * @Description 求数字阶乘(for循环版)
 * @Author 2214361854
 * @Date 2022/5/27 10:41
 * @Version 1.0
 */
public class Demo22 {
    /**
     * 需求:接收用户输入的数字,计算该数字的阶乘结果
     * 已知:负数不可以有阶乘,0的阶乘结果是1,
     * 5阶乘 = 5 x 4 x 3 x 2 x 1
     */
    public static void main(String[] args) {
        System.out.println("输入正整数：");
        int n = new Scanner(System.in).nextInt();
        System.out.println(n + "的阶乘：" + cjFor(n));
        System.out.println(n + "的阶乘：" + cjDg(n));
    }

    /**
     * 递归
     *
     * @param num
     */
    private static int cjDg(int num) {
        int sum = 1;
        if (num < 0) {
            throw new IllegalArgumentException("必须为正整数!");
        }
        if (num == 1) {
            return 1;
        } else {
            sum = num * cjDg(num - 1);
            return sum;
        }
    }

    /**
     * 循环
     *
     * @param num
     */
    private static long cjFor(int num) {
        if (num < 0) {
            throw new IllegalArgumentException("必须为正整数!");
        }
        if (num == 0) {
            return 1;
        }
        long r = 1;
        for (int i = num; i >= 1; i--) {
            r *= i;
        }
        return r;
    }

}
